<template>
  <div>
    <!-- <van-search
      v-model="searchText"
      placeholder="搜索队伍"
      @search="loadData"
    /> -->
    <van-tabs v-model:active="active" @change="onTabChange" animated>
      <van-tab name="public"
        ><template #title>
          <van-icon name="eye-o" color="blue" size="16px" />
          公开
        </template></van-tab
      >
      <van-tab name="private"
        ><template #title>
          <van-icon name="closed-eye" color="red" size="16px" />
          加密
        </template></van-tab
      >
    </van-tabs>
    <div style="margin-bottom: 16px" />
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :offset="130"
      @load="onLoad"
    >
      <team-card-list :teamList="teamList" qd="0" :userId="0" />
    </van-list>

    <van-button
      class="add-button"
      type="primary"
      icon="plus"
      @click="toAddTeam"
    />
    <van-empty v-if="teamList?.length < 1" />
  </div>
</template>

<script setup lang="ts">
import myAxios from "../plugins/myAxios";
import TeamCardList from "../components/TeamCardList.vue";
import { onMounted, ref } from "vue";
import { showFailToast } from "vant";
import { useRouter } from "vue-router";
import { UserType } from "../models/user";
import { TeamType } from "../models/team";
import { getCurrentUser } from "../services/user";

/**
 * 切换查询状态
 */
const active = ref("public"); //根据据队伍状态查询
const searchText = ref(""); //搜索标签
const teamList = ref([]); //用作展示的数组
const onTabChange = (name) => {
  teamList.value = [];
  if (name === "public") {
    loadData(searchText.value, 0);
  } else {
    loadData(searchText.value, 2);
  }
};

const teamListData = ref([]); //接收后端数据的原数组
const loadData = async (val = "", status = 0) => {
  teamListData.value = await myAxios
    .get("/team/list", {
      params: {
        searchText: val,
        pageNum: 1,
        status,
      },
    })
    .then(function (response) {
      return response?.data;
    })
    .catch(function (error) {
      showFailToast("小智遗憾告知:请求失败!!请刷新重试");
    });
  if (teamListData.value.length !== 0) {
    onLoad();
  }
};

const loading = ref(false); //是否处于加载状态
const finished = ref(false); //是否完成加载
const onLoad = () => {
  if (teamListData.value.length !== 0) {
    const teamArr = teamListData.value.splice(0, 8); //过渡的数组
    if (teamListData.value.length === 0) {
      finished.value = true;
    }
    teamArr.forEach((team: TeamType) => {
      teamList.value.push(team);
    });
  }
};

// 跳转到创建队伍页
const router = useRouter();
const toAddTeam = () => {
  router.push({
    path: "/team/update",
    query: {
      id: 0,
      userId: currentUser.value.id,
    },
  });
};

const currentUser = ref({} as UserType); //当前用户
onMounted(async () => {
  currentUser.value = await getCurrentUser("1");
  loadData();
});
</script>

<style scoped>
@import "../assets/css/public.css";
</style>
